<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>API测试</title>
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
	<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
	<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
	<script src="https://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js" type="text/javascript"></script>
	<style type="text/css">
		body{padding-top:10px;}
		.list-group-item{cursor: pointer;}
	</style>
</head>
<body ng-app="apiApp" ng-controller="apiCtrl">
	<div class="container">
		<div class="input-group">
			<span class="input-group-addon">HOST:</span>
			<input type="text" class="form-control" ng-model="api.host" />
		</div>
		<br/>
		<div class="input-group"  ng-mouseover ="showHistory(true);" >
			<span class="input-group-addon" >&nbsp;&nbsp;API:</span>
			<input class="form-control" type="text" ng-model="api.url" ng-blur="changeApi();" ng-keyup="keyup($event)" id="apiIpt"/>
			<ul class="dropdown-menu  pull-right list-group" ng-style="historyStyle" ng-mouseleave ="showHistory(false);">
				<li class="list-group-item" ng-repeat="urlItem in apiHistory" ng-click=setApi(urlItem); >
					<span ng-bind="urlItem"></span>
					<button type="button" class="close" aria-label="close" ng-click="delHistory(urlItem);">&times;</button>
				</li>
          	</ul>
		</div>
		<br/>
		<table class="table table-striped">
			<tbody>
				<tr ng-repeat="(index,row) in params" >
					<td colspan="2" >
						<input type="text" name="" class="form-control" ng-model="params[index].field">
					</td>
					<td colspan="2" >
						<input type="text" name="" class="form-control" ng-model="params[index].value">
					</td>
					<td colspan="1">
						<button class="btn btn-primary btn-sm" ng-click="delRow(index);">-</button>
					</td>
				</tr>
				<tr>
					<td colspan="5">
						<button class="btn btn-primary" ng-click="addRow();">增加</button>
						<button class="btn btn-primary" ng-click=send();>发送</button>
					</td>
				</tr>
<!-- 				<tr>
					<td colspan="5">
						<button class="btn btn-primary" ng-click="fetchTime()">当前时间戳</button>
					</td>
				</tr> -->
				
				
			</tbody>
		</table>
		<div id="rtnContent"></div>

	</div>
	<script type="text/javascript">
		angular.module('apiApp', [])
		.controller('apiCtrl',function($scope){
			$scope.historyStyle={};//api输入框的历史提示框的样式对象
			$scope.apiHistory = [];//api输入框的输入历史
			var apiLog = [];
			// $scope.apiHistory=[];
			if( localStorage.apiHistory ){
				$scope.apiHistory = JSON.parse(localStorage.apiHistory);
				$scope.apiHistory.sort();
				apiLog  = JSON.parse(localStorage.apiHistory);
			}
			$scope.api={
				host:location.origin+'/',
				url:'',
			}
			$scope.params=[{field:'',value:''}];
			// 获取最后一次请求的API的数据
			var lastRequest = localStorage.getItem('lastRequest');
			if( lastRequest ){
				$scope.api.url = lastRequest;
				var api = localStorage.getItem(lastRequest);
				if( api ){
					$scope.params = JSON.parse(api);
				}
			}
			if( localStorage.host ){
				$scope.api.host = localStorage.host
			}
			// 当url输入框onblur时触发,修改api的参数
			$scope.changeApi = function(){
				var params = localStorage.getItem($scope.api.url);
				if( params ){
					$scope.params = JSON.parse(params);
				}
				$scope.showHistory(false);
			}
			// api输入框有输入时
			$scope.keyup = function(e){
				var keycode = window.event ? e.keyCode : e.which;
				if( keycode==13 ){//回车键
					$scope.changeApi();
				}else{
					var urlList = [];
					var input   = $scope.api.url;
					for (var i = 0; i < apiLog.length; i++) {
						if(apiLog[i].indexOf(input)!==-1){
							urlList.push(apiLog[i]);
						}
					}
					$scope.apiHistory = urlList;
				}
			}
			// 显示输入历史下拉框
			$scope.showHistory = function(isShow){
				// $scope.historyStyle.display = 'block' ;
				$scope.historyStyle.display = isShow ? 'block' : 'none';
				$scope.historyStyle.width = $('#apiIpt').outerWidth();
			}
			// 删除历史记录
			$scope.delHistory = function(sUrl){
				var index = $scope.apiHistory.indexOf(sUrl);
				if( index>=0 ){
					$scope.apiHistory.splice(index, 1);
					localStorage.apiHistory = JSON.stringify($scope.apiHistory);
				}
				localStorage.removeItem(sUrl);
			}
			// 设置api
			$scope.setApi = function (sUrl){
				$scope.api.url = sUrl;
				$scope.changeApi();
				$scope.showHistory(false);
			}
			// 增加一行
			$scope.addRow = function(){
				$scope.params.push({field:'',value:''});
			}
			// 删除一行
			$scope.delRow = function(index){
				$scope.params.splice(index, 1);
			}
			// 获取当前时间戳
			$scope.fetchTime = function(e){
				var time = parseInt((new Date().getTime())/1000);
				console.log(time);
				var e = document.activeElement;
				console.log(e);
			}
			// 发送请求
			$scope.send = function(){
				var data={};
				var row={};
				for(var x in $scope.params){
					row=$scope.params[x];
					if(row.field){
						data[row.field]=row.value;
					}
				}

				localStorage.setItem('lastRequest',$scope.api.url);
				localStorage.setItem($scope.api.url,JSON.stringify($scope.params));
				localStorage.setItem('host',$scope.api.host);

				var apiHistory = localStorage.getItem('apiHistory');
				if( apiHistory ){
					apiHistory = JSON.parse(apiHistory);
					if( apiHistory.indexOf($scope.api.url)<0 ){
						apiHistory.push($scope.api.url);
						apiHistory.sort();
						localStorage.setItem('apiHistory',JSON.stringify(apiHistory));
					}
				}else{
					apiHistory = [];
					apiHistory.push($scope.api.url);
					localStorage.setItem('apiHistory',JSON.stringify(apiHistory));
				}
				$scope.apiHistory = apiLog = apiHistory;

				$.ajax({
					url:$scope.api.host+$scope.api.url,
					data:data,
					method:'post',
				}).done(function(rtn){
					var type = typeof(rtn);
					// 如果是字符串,尝试解析为JSON对象
					// 如果解析失败,直接以string形式显示
					if( 'string'===type ){
						try{
							rtn = JSON.parse(rtn);
						}catch(e){
							showContent(rtn,'string');
							return;
						}
					}
					if( rtn.error !==undefined && rtn.error !=0 ){
						alert('Error:['+rtn.error+']'+rtn.msg);
					}
					showContent(rtn,'object');
				}).fail(function(rtn,status,e){
					console.log([rtn,status,e]);
					alert(status+':'+e);
					showContent(rtn.responseText,'string');
				});
			}
		})

		function showContent(content,type){
			var type = type || typeof(content);
			var html = '';
			if( 'object'===type ){
				html = '<pre>'+JSON.stringify(content,null,2)+'</pre>';
			}else{
				html = $('<iframe></iframe>').prop({
					srcdoc:content,
					width:($(document.body).width()-100)+'px',
					height:($(window).height()-250)+'px',
				});
			}
			$('#rtnContent').html(html);
		}


	</script>
</body>
</html>
